package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.top10.bean.JwtUtil;
import com.top10.bean.PageBean;
import com.top10.bean.ResponseBean;
import com.top10.cache.RedisUtil;
import com.top10.common.Const;
import com.top10.common.OrderConst;
import com.top10.entity.*;
import com.top10.entity.vo.*;
import com.top10.service.*;
import com.top10.service.impl.ConsigneeServiceImpl;
import com.top10.service.impl.TlfPayService;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author sny
 * @Package com.top10.controller.mobile
 * @date 2018/10/5
 */
@RestController
@RequestMapping("/manager/top10/order")
public class OrderController {


    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IOrderDetailedService iOrderDetailedService;

    @Autowired
    IUserService iUserService;
    @Autowired
    @Qualifier("tlfPayService")
    private TlfPayService tlfPayService;

    @Autowired
    private IShopService iShopService;

    @Autowired
    private ICommentService iCommentService;

    @Autowired
    private IGoodsDetailedService iGoodsDetailedService;
    @Autowired
    private IUserDepositService iUserDepositService;
    @Autowired
    IUserWithdrawalService userWithdrawalService;
    @Autowired
    private ISpecialPriceService iSpecialPriceService;
    @Autowired
    private IUserCartService iUserCartService;
    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private  ICouponUserService iCouponUserService;
    @Autowired
    private ICouponService iCouponService;
    @Autowired
    IUserCartService userCartService;
    @Autowired
    IShopService shopService;
    @Autowired
    private ConsigneeServiceImpl consigneeService;


    // private static ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/listall")
    public ResponseBean listall(long type,PageBean pageBean,HttpServletRequest request){

       String userUuid = JwtUtil.getUuidByToken(request);
       // String userUuid="2c5006a745b1444a8d35eebb50e44960";
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        Page page=PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<OrderVo> orderVos=iOrderService.selectlistorder(user.getUuid(),type);
       // int page=orderVos.size();
        pageBean=new PageBean(pageBean.getPageNum(),pageBean.getPageSize(), (int) page.getTotal());
        return ResponseBean.createSuccess().addData("OrderVo",orderVos).addData("pageBean",pageBean);
    }


    @Transactional
    @PostMapping("/createorder")
    public ResponseBean createorder(HttpServletRequest request) throws Exception {



        String data=request.getParameter("orderlist");
        Gson gson = new GsonBuilder().serializeNulls()
                .setPrettyPrinting()
                .disableHtmlEscaping()
                .create();
        List<OrderCreateVo> orderlist = gson.fromJson(data, new TypeToken<List<OrderCreateVo>>(){}.getType());

        //合并支付payid
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String payid = sdf.format(new Date()) + RandomUtils.makeRandomDigit6() + RandomUtils.getNBitRandomDigit(4);
        double actulaPrice=0;

        List<OrderDetailed> orderDetailedList=new ArrayList();
        List<Order> orders=new ArrayList();
        Map<String,Object> orderpayMap=new HashMap<>();
        for(OrderCreateVo orderCreate:orderlist){

            System.out.println(orderCreate.toString());
            /* Order order=iOrderService.create(orderCreate,request);*/

            //循环内代替create方法

             String userUuid = JwtUtil.getUuidByToken(request);

            //   String userUuid ="95153988018047CFA4D466F799FA9C4E";
             User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));


            //订单商品总数量
            int aggregateAmount=0;

            //订单总金额
            double aggregatePrice =0 ;

            //订单小计支付金额（包括邮费、减去优惠券、积分）
            double actual_price=0;

            DecimalFormat decimalFormat = new DecimalFormat("#.00");

            Order order=new Order();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

            String orderid=simpleDateFormat.format(new Date())+RandomUtils.makeRandomDigit6();
            String orderuuid=RandomUtils.makeUUID();

            //处理代理商的商店订单
            Shop shop = shopService.selectOne(new EntityWrapper<Shop>().eq("uuid",orderCreate.getShopUuid()));
            if (null != shop && shop.getShopType() == 4) {
                Consignee consignee=consigneeService.selectConsigneeone(orderCreate.getConsigneeUuid());
                String province=consignee.getProvince();
                String city=consignee.getCity();
                String district=consignee.getDistrict();
                String uuid = shopService.getAgentUUidone(province, city, district, orderCreate.getShopUuid());
                order.setShopUuid(uuid);
            }else{
                order.setShopUuid(orderCreate.getShopUuid());
            }

            order.setUuid(orderuuid);
            order.setOrderid(orderid);


            for(OrderCreateDetailedVo orderDetailed:orderCreate.getOrderDetailCreateVo())
            {

                OrderDetailed orderDetail =new OrderDetailed();
                List<SpecialPrice> speciaGood=iSpecialPriceService.selectList(new EntityWrapper<SpecialPrice>().eq("isdeleted", Const.SpecialIsNotDeleted)
                        .eq("goods_uuid",orderDetailed.getGoodsUuid()).gt("end_time",new Date()));

                //判断是否为特价商品
                if(speciaGood.size()!=0) {

                    Goods good2 = iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", orderDetailed.getGoodsUuid())
                            .eq("isdeleted", Const.IsNotDelete).eq("shop_uuid", orderCreate.getShopUuid()));
                    GoodsDetailed goodsDetailed = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid", orderDetailed.getGoodsUuid()));
                  /* String sku= goodsDetailed.getSku();
                    List<SkuVo> skuvo=gson.fromJson(sku, new TypeToken<List<SkuVo>>(){}.getType());
                    SkuVo skuVo=new SkuVo();
                    for (int i=0;i<skuvo.size();i++){
                            if(skuvo.get(i).getKeyin().contains(orderDetailed.getAttributes())){
                               skuVo=skuvo.get(i);
                               break;
                            }
                    }*/



                    if (good2 == null || goodsDetailed == null) {
                        return ResponseBean.createSuccess(good2.getName() + "已下架,或者非该商家商品");
                    }

                    int i=0;
                    double subtotal=0;
                    for (SpecialPrice speciaGoods : speciaGood) {

                        i++;
                        //如果是多件惠商品
                        if (speciaGoods.getType().equals(1)) {


                            Integer Quantity = orderDetailed.getQuantity();
//                            if (Quantity > speciaGoods.getLimitedNumber()) {
//                                return ResponseBean.createError("商品数量不能超过限购最大数量");
//                            }
                            //满足条件，即可享受多件惠的价格
                            if (Quantity >= speciaGoods.getMinNumber()&&speciaGoods.getLimitedNumber()>=Quantity) {


                                orderDetail.setUuid(RandomUtils.makeUUID());
                                orderDetail.setOrderUuid(orderuuid);
                                orderDetail.setGoodsName(good2.getName());
                                orderDetail.setCreator(user.getUuid());

                                orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                                orderDetail.setAttributes(orderDetailed.getAttributes());
                                orderDetail.setPrice(speciaGoods.getSpecialPrice());
//                            Integer Quantity1=orderDetailed.getQuantity();
                                orderDetail.setQuantity(Quantity);



                                //该商品总价
                                subtotal = Double.parseDouble(decimalFormat.format(speciaGoods.getSpecialPrice() * orderDetailed.getQuantity()));
                                orderDetail.setSubtotal(subtotal);


                                //实际需要支付的总价
                                orderDetail.setActualSubtotal(subtotal);
                                orderDetail.setCreatetime(new Date());





                                //库存不足的时候要返回商品名给前端
                                Goods goods = iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", orderDetailed.getGoodsUuid())
                                        .eq("isdeleted", Const.IsNotDelete));
                                //判断库存数量是否足够
                                GoodsDetailed stock = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted", Const.IsNotDelete)
                                        .eq("goods_uuid", orderDetailed.getGoodsUuid()));
                                if (stock == null) {
                                    return ResponseBean.createSuccess("库存中不存在" + goods.getName() + "该商品");
                                }
                                if (stock.getStock() < orderDetailed.getQuantity() || stock.getStock() < 1) {

                                    return ResponseBean.createSuccess(goods.getName() + "库存不足");
                                }
                                //商品总价
                                aggregatePrice += subtotal;

                                //商品总价
                                actual_price += subtotal;

                                //商品总数
                                aggregateAmount += Quantity;

                                iOrderDetailedService.insert(orderDetail);


                                //减掉库存
                                Integer actualstock = stock.getStock() - orderDetailed.getQuantity();
                                stock.setStock(actualstock);
                                stock.setUpdatetime(new Date());
                                iGoodsDetailedService.updateById(stock);
                                break;
                            }


                            //不满足条件，即使用原价
                            if (Quantity < speciaGoods.getMinNumber()||(speciaGood.size()==i&&Quantity >speciaGoods.getLimitedNumber())) {

                                Goods sgoods = iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", orderDetailed.getGoodsUuid())
                                        .eq("isdeleted", Const.IsNotDelete).eq("shop_uuid", orderCreate.getShopUuid()));
                                GoodsDetailed sgoodsDetailed = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid", orderDetailed.getGoodsUuid()));
                                if (sgoods == null || sgoodsDetailed == null) {

                                    return ResponseBean.createSuccess("商品已下架,或者非该商家商品");
                                }

                                String[] line =orderDetailed.getAttributes().split(",");
                                SkuVo skuVo=new SkuVo();
                                if(goodsDetailed.getSku()!=null){
                                    String sku= goodsDetailed.getSku();
                                    List<SkuVo> skuvo=gson.fromJson(sku, new TypeToken<List<SkuVo>>(){}.getType());
                                    for (int a=0;a<=skuvo.size()-1;a++){
                                        int c=-1;
                                        for(int j=0;j<=line.length-1;j++){
                                            if(skuvo.get(a).getKeyin().contains(line[j])){
                                                c++;
                                                if(c==line.length-1){
                                                    skuVo=skuvo.get(a);
                                                }
                                            }

                                        }

                                    }
                                }


                                orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                                orderDetail.setUuid(RandomUtils.makeUUID());
                                orderDetail.setOrderUuid(orderuuid);
                                orderDetail.setGoodsName(sgoods.getName());


                                orderDetail.setAttributes(orderDetailed.getAttributes());
                                /*orderDetail.setPrice(goodsDetailed.getPrice());*/

                                orderDetail.setPrice(skuVo.getSkuprice());//goodsDetailed.getPrice() skuVo.getSkuprice()

                                Integer sQuantity = orderDetailed.getQuantity();
                                orderDetail.setQuantity(sQuantity);


                             /*   double subtotal;*/
                                //该商品价格
                                if (skuVo!=null){
                                    subtotal = Double.parseDouble(decimalFormat.format(skuVo.getSkuprice() * orderDetailed.getQuantity()));
                                }else{
                                    subtotal = Double.parseDouble(decimalFormat.format(goodsDetailed.getPrice() * orderDetailed.getQuantity()));
                                }
                         /*       //该商品价格
                                 subtotal = Double.parseDouble(decimalFormat.format(goodsDetailed.getPrice() * orderDetailed.getQuantity()));*/

                                orderDetail.setSubtotal(subtotal);
                                orderDetail.setCreator(user.getUuid());
                                orderDetail.setActualSubtotal(subtotal);
                                orderDetail.setCreatetime(new Date());
                                orderDetail.setRemark(orderDetailed.getRemark());


                                //  判断库存数量是否足够
                                GoodsDetailed stock = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted", Const.IsNotDelete)
                                        .eq("goods_uuid", orderDetailed.getGoodsUuid()));
                                if (stock == null) {
                                    return ResponseBean.createSuccess("库存中不存在" + sgoods.getName() + "该商品");
                                }
                                if (stock.getStock() < orderDetailed.getQuantity() || stock.getStock() < 1) {

                                    return ResponseBean.createSuccess(sgoods.getName() + "库存不足");

                                }

                                //商品总价
                                aggregatePrice += subtotal;

                                //商品总价
                                actual_price += subtotal;

                                //商品总数
                                aggregateAmount += Quantity;

                                iOrderDetailedService.insert(orderDetail);

                                // 减掉库存
                                Integer actualstock = stock.getStock() - orderDetailed.getQuantity();

                                stock.setStock(actualstock);
                                stock.setUpdatetime(new Date());
                                iGoodsDetailedService.updateById(stock);
                                break;
                            }
                        }

                        //如果不是多件惠商品
                        if (!speciaGoods.getType().equals(1)) {

                            if (orderDetailed.getQuantity() > speciaGoods.getLimitedNumber()) {
                                return ResponseBean.createError("不能超过限购的数量");
                            }

                            orderDetail.setUuid(RandomUtils.makeUUID());
                            orderDetail.setOrderUuid(orderuuid);
                            orderDetail.setGoodsName(good2.getName());
                            orderDetail.setCreator(user.getUuid());

                            orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                            orderDetail.setAttributes(orderDetailed.getAttributes());
                            orderDetail.setPrice(speciaGoods.getSpecialPrice());
                            Integer Quantity = orderDetailed.getQuantity();
                            orderDetail.setQuantity(Quantity);



                           //该商品总价
                            subtotal = Double.parseDouble(decimalFormat.format(speciaGoods.getSpecialPrice() * orderDetailed.getQuantity()));
                            orderDetail.setSubtotal(subtotal);

                            //实际需要支付的总价
                            orderDetail.setActualSubtotal(subtotal);
                            orderDetail.setCreatetime(new Date());

                            //库存不足的时候要返回商品名给前端
                            Goods goods = iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", orderDetailed.getGoodsUuid())
                                    .eq("isdeleted", Const.IsNotDelete));
                            //判断库存数量是否足够
                            GoodsDetailed stock = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted", Const.IsNotDelete)
                                    .eq("goods_uuid", orderDetailed.getGoodsUuid()));
                            if (stock == null) {
                                return ResponseBean.createSuccess("库存中不存在" + goods.getName() + "该商品");
                            }
                            if (stock.getStock() < orderDetailed.getQuantity() || stock.getStock() < 1) {

                                return ResponseBean.createSuccess(goods.getName() + "库存不足");
                            }
                            //商品总价
                            aggregatePrice += subtotal;

                            //商品总价
                            actual_price += subtotal;

                            //商品总数
                            aggregateAmount += Quantity;

                            iOrderDetailedService.insert(orderDetail);


                            //减掉库存
                            Integer actualstock = stock.getStock() - orderDetailed.getQuantity();
                            stock.setStock(actualstock);
                            stock.setUpdatetime(new Date());
                            iGoodsDetailedService.updateById(stock);
                            //清除掉购物车中该商品

                            UserCart userCart = iUserCartService.selectOne(new EntityWrapper<UserCart>().eq("user_uuid", user.getUuid())
                                    .eq("goods_uuid", orderDetailed.getGoodsUuid()).eq("isdeleted", 0));
                            if (userCart != null) {
                                userCart.setIsdeleted(true);
                                iUserCartService.updateById(userCart);
                            }
                            break;
                        }

//                        if(speciaGood.size()==i && subtotal==0){
//                            return ResponseBean.createError("不能超过最大限购数量");
//                        }
                    }
                }


              else {

                    Goods goods =iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid",orderDetailed.getGoodsUuid())
                            .eq("isdeleted",Const.IsNotDelete).eq("shop_uuid",orderCreate.getShopUuid()));
                    GoodsDetailed goodsDetailed=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid",orderDetailed.getGoodsUuid()));

                    String[] line =orderDetailed.getAttributes().split(",");

                    SkuVo skuVo=new SkuVo();
                    if(goodsDetailed.getSku()!=null){
                        String sku= goodsDetailed.getSku();
                        List<SkuVo> skuvo=gson.fromJson(sku, new TypeToken<List<SkuVo>>(){}.getType());
                        for (int i=0;i<=skuvo.size()-1;i++){
                            int c=-1;
                            for(int j=0;j<=line.length-1;j++){
                                if(skuvo.get(i).getKeyin().contains(line[j])){
                                    c++;
                                    if(c==line.length-1){
                                        skuVo=skuvo.get(i);
                                    }
                                }

                            }

                        }
                    }


       /*             SkuVo skuVo=new SkuVo();
                    if(goodsDetailed.getSku()!=null){
                        String sku= goodsDetailed.getSku();
                        List<SkuVo> skuvo=gson.fromJson(sku, new TypeToken<List<SkuVo>>(){}.getType());
                        for (int i=0;i<skuvo.size();i++){
                            if(skuvo.get(i).getKeyin().contains(orderDetailed.getAttributes())){
                                skuVo=skuvo.get(i);
                                break;
                            }
                        }
                    }*/



                    if(goods==null || goodsDetailed==null){

                        return ResponseBean.createSuccess("商品已下架,或者非该商家商品");
                    }
                    orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                    orderDetail.setUuid(RandomUtils.makeUUID());
                    orderDetail.setOrderUuid(orderuuid);
                    orderDetail.setGoodsName(goods.getName());


                    orderDetail.setAttributes(orderDetailed.getAttributes());

                    orderDetail.setPrice(skuVo.getSkuprice());//goodsDetailed.getPrice() skuVo.getSkuprice()

                    Integer Quantity=orderDetailed.getQuantity();
                    orderDetail.setQuantity(Quantity);


                     double subtotal;
                    //该商品价格
                    if (skuVo!=null){
                        subtotal = Double.parseDouble(decimalFormat.format(skuVo.getSkuprice() * orderDetailed.getQuantity()));
                    }else{
                        subtotal = Double.parseDouble(decimalFormat.format(goodsDetailed.getPrice() * orderDetailed.getQuantity()));
                    }


                    orderDetail.setSubtotal(subtotal);
                    orderDetail.setCreator(user.getUuid());
                    orderDetail.setActualSubtotal(subtotal);
                    orderDetail.setCreatetime(new Date());
                    orderDetail.setRemark(orderDetailed.getRemark());


                    //  判断库存数量是否足够
                    GoodsDetailed stock=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted",Const.IsNotDelete)
                            .eq("goods_uuid",orderDetailed.getGoodsUuid()));
                    if(stock==null){
                        return ResponseBean.createSuccess("库存中不存在"+goods.getName()+"该商品");
                    }
                    if(stock.getStock()<orderDetailed.getQuantity() || stock.getStock()<1){

                        return ResponseBean.createSuccess(goods.getName()+"库存不足");

                    }

                    //商品总价
                    aggregatePrice+=subtotal;

                    //商品总价
                    actual_price+=subtotal;

                    //商品总数
                    aggregateAmount+=Quantity;

                    iOrderDetailedService.insert(orderDetail);

                    // 减掉库存
                    Integer actualstock =stock.getStock()-orderDetailed.getQuantity();

                    stock.setStock(actualstock);
                    stock.setUpdatetime(new Date());
                    iGoodsDetailedService.updateById(stock);

                    UserCart userCart=iUserCartService.selectOne(new EntityWrapper<UserCart>().eq("user_uuid",user.getUuid())
                            .eq("goods_uuid",orderDetailed.getGoodsUuid()).eq("isdeleted",0));
                    if(userCart!=null){
                        userCart.setIsdeleted(true);
                        iUserCartService.updateById(userCart);
                    }
                }


            }

            System.out.println(orderCreate.getCard_coupons_uuid());
            if(!orderCreate.getCard_coupons_uuid().equals("1")) {


//                //减去该商品优惠券价格
//                Coupon coupon = iCouponService.selectOne(new EntityWrapper<Coupon>().eq("uuid", orderCreate.getCardCouponsUuid()).ge("endDate", new Date()));
                Coupon coupon1 = iCouponService.selectOne(new EntityWrapper<Coupon>().eq("uuid", orderCreate.getCard_coupons_uuid()));
                CouponUser couponUser = iCouponUserService.selectOne(new EntityWrapper<CouponUser>().eq("couponId",coupon1.getId())
                        .eq("userId",user.getUuid()));
                if (couponUser==null) {
                    return ResponseBean.createError("该优惠券不存在");
                }
                Coupon coupon = iCouponService.selectOne(new EntityWrapper<Coupon>().eq("id", couponUser.getCouponId()).ge("endDate", new Date()));
                if (coupon == null) {
                    return ResponseBean.createError("该优惠券已过期");

                }
                   BigDecimal c=coupon.getRequirementAmount();
                if (coupon.getRequirementAmount().doubleValue() > aggregatePrice) {
                    return ResponseBean.createSuccess("不满足优惠券的使用条件");
                }


                Double couponprice = coupon.getAmount().doubleValue();


                //该优惠券的总数量减一
                // coupon.setCouponNum(coupon.getCouponNum() - 1);

                //减去优惠券的价格
                actual_price = actual_price - couponprice;

                //  设置用户优惠券已使用
                couponUser.setIsUsed(String.valueOf(1));

                iCouponUserService.updateById(couponUser);
            }
            //积分
            BigDecimal integral= new BigDecimal(orderCreate.getIntegral()/10).setScale(2, RoundingMode.UP);

            //  减去积分
            actual_price=actual_price-integral.doubleValue();


            //增加运费
            actual_price=actual_price+orderCreate.getExpressPrice();
            //减去用户总积分
            user.setPoint(BigDecimal.valueOf(user.getPoint().doubleValue()-orderCreate.getIntegral().doubleValue()));

            //更新用户积分
            iUserService.updateById(user);

            if(actual_price<0){
                actual_price=0;
            }

            BigDecimal bd = new BigDecimal(actual_price);
            double d = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            order.setUserUuid(user.getUuid());
            order.setConsigneeUuid(orderCreate.getConsigneeUuid());
            order.setExpressPrice(orderCreate.getExpressPrice());
            //商品总价，还没减去优惠券价格、积分
            order.setAggregateAmount(aggregatePrice);
            //用户实际需要支付的价格
            order.setActualPrice(d);

            //该订单的商品总数
            order.setsQuantity(aggregateAmount);
            order.setIntegral(orderCreate.getIntegral());
            order.setCardCouponsUuid(orderCreate.getCard_coupons_uuid());
            //order.setDeliveryUuid(orderCreate.getDeliveryUuid());
            order.setStatus(0);
            //order.setOrderType(1);
            //order.setProvince(orderCreate.getProvince());
            order.setCreatetime(new Date());
            order.setIsdeleted(false);
            order.setPaySellerStatus(false);
            //代支付
            order.setPaytype(3);
            order.setCreator(user.getUuid());



            //循环内
            iOrderService.insert(order);
            orders.add(order);
        }

        for(Order orderpay:orders){
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("orderid",orderpay.getOrderid()));
            order.setPayid(payid);
            order.setCreatetime(new Date());
            iOrderService.updateById(order);
            actulaPrice+=order.getActualPrice();
        }

        for(Order orderlists:orders){

            //撤销购物车的列表
            UserCartGoodsVo goods=iOrderDetailedService.selectGoods(orderlists.getId());
            if(goods!=null){
                if(goods.getAttributes().equals("{}") || goods.getAttributes()==null){
                    userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",orderlists.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("isdeleted",false));
                }else{
                    userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",orderlists.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("attributes",goods.getAttributes()).eq("ideleted",false));
                }
            }


            List<OrderPayVo> orderPayVoslist=iOrderService.selectpaylist(orderlists.getUuid());
            orderpayMap.put(orderlists.getUuid(),orderPayVoslist);
        }
        BigDecimal bd = new BigDecimal(actulaPrice);
        double dactulaPrice = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        return ResponseBean.createSuccess().addData("orderpayMap",orderpayMap).addData("payid",payid).addData("dactulaPrice",dactulaPrice);
    }


    @PostMapping("/orderdetail")
    public ResponseBean orderdetail(String orderuuid){

        if(orderuuid==null){
            return ResponseBean.createError("orderid不能为空");
        }
        //List<ShowOrderVo> showOrderDetailVo= iOrderService.selectOrderDetail(orderuuid);
        try{
            ShowOrderVo showOrderDetailVo= iOrderService.selectOrderDetail(orderuuid);
            if(showOrderDetailVo==null){
                return ResponseBean.createError("不存在该订单");
            }else {
                return ResponseBean.createSuccess().addData("showOrderDetailVo",showOrderDetailVo);
            }
        }catch (Exception e){
              return ResponseBean.createException("数据库异常,出现重复的数据");
        }

    }





    @PostMapping("/test")
    public ResponseBean test(){

        return  ResponseBean.createSuccess();

    }


    /***
     * 取消订单
     * @param
     * @return
     */
    @PostMapping("/cancelorder")
    public ResponseBean cancelorder(String orderid){
        if(orderid==null){
            return ResponseBean.createError("订单id不能为空");
        }try{
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("id",orderid));
            if(order==null){
                return ResponseBean.createError("不存在该订单");
            }
            if(order.getStatus()==0) {
                order.setStatus(OrderConst.orderstatus8);
                order.setUpdatetime(new Date());
                iOrderService.updateById(order);
                return ResponseBean.createSuccess("取消订单成功");

            }else {
                return ResponseBean.createError("取消订单失败");
            }
        }catch(Exception e){
            return ResponseBean.createException("数据库异常,出现重复的数据");
        }

    }


    @PostMapping("/cancelRefund")
    public ResponseBean cancelRefund(Long id){
        if(id==null){
            return ResponseBean.createError("订单id不能为空");
        }
        try{
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("id",id));
            if(order==null){
                return ResponseBean.createError("该订单不存在或者数据异常");
            }
            if(order.getStatus()==5){
                //返回原来的订单状态
                order.setStatus(order.getOldStatus());
                order.setUpdatetime(new Date());
                iOrderService.updateById(order);
                return ResponseBean.createSuccess("用户取消退款成功");
            }
            return ResponseBean.createError("用户取消退款失败");
        }catch (Exception e){
            return ResponseBean.createException("数据库异常,出现重复的数据");
        }

    }


    /***
     * 确认收货
     * @param
     * @return
     */
    @PostMapping("/confirmorder")
    public ResponseBean confirmorder(String orderid){

        if(orderid==null){
            return ResponseBean.createError("订单id不能为空");
        }
        try{
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("id",orderid));
            if(order==null){
                return ResponseBean.createError("该订单不存在");
            }
            //商品状态为3，允许确认收货，否则不允许,要改为2,客户自己不知道怎么去操作
            if(order.getStatus().equals(2)){
                //更新商品状态
                order.setStatus(OrderConst.orderstatus4);
                order.setUpdatetime(new Date());
                iOrderService.updateById(order);


                Shop shop=iShopService.selectOne(new EntityWrapper<Shop>().eq("uuid",order.getShopUuid()));

                if(shop==null){
                    return ResponseBean.createError("不存在该商店");
                }
                Double orderPrice=order.getActualPrice();

               // User user=iUserService.selectById(shop.getUserUuid());
                User user=iUserService.selectOne(new EntityWrapper<User>().eq("uuid",shop.getUserUuid()));
                if(user==null){
                    return ResponseBean.createError("不存在该商店");
                }

                user.setMoney(BigDecimal.valueOf(user.getMoney().doubleValue()+orderPrice));
                iUserService.updateById(user);
                return ResponseBean.createSuccess("确认收货成功");
            }else{
                return ResponseBean.createError("该订单的状态不是已发货，确认收货失败");
            }
        }catch (Exception e){
            return ResponseBean.createException("数据库异常,出现重复的数据");
        }

    }

    /***
     * 申请退款
     * @param
     * @return
     */
    @PostMapping("/applyRefund")
    public ResponseBean applyRefund(String orderid){
        if(orderid==null){
            return ResponseBean.createError("订单id不能为空");
        }try{
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("id",orderid));
            if(order==null){
                return ResponseBean.createError("该订单不存在");
            }
            //记录申请退款时的订单状态
            order.setOldStatus(order.getStatus());
            order.setStatus(OrderConst.orderstatus5);
            iOrderService.updateById(order);
            return ResponseBean.createSuccess("申请退款成功");
        }catch (Exception e){
            return ResponseBean.createException("数据库异常,出现重复的数据");
        }

    }

    /**
     * 获取未评价的商品
     * @return
     */
    @PostMapping("/getuncommentgoods")
    public ResponseBean getuncommentgoods(HttpServletRequest request){
        String userUuid = JwtUtil.getUuidByToken(request);
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));

        List<Order> orders=iOrderService.selectList(new EntityWrapper<Order>().eq("user_uuid",user.getUuid())
                .eq("status",OrderConst.orderstatus4));
        List<Order> unCommentOrder =new ArrayList();
        List<OrderDetailedWithGoodsUuid> orderDetailedsWithGoodsuuid=new ArrayList();

        List<OrderDetailed> orderDetaileds=new ArrayList<>();

        for(Order order:orders){

            List<OrderDetailed> orderDetailedsLists=iOrderDetailedService.selectList(new EntityWrapper<OrderDetailed>().eq("order_uuid",order.getUuid()));
            for(OrderDetailed orderDetailedList:orderDetailedsLists){
                GoodsDetailed goodsDetailed=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("uuid",orderDetailedList.getGoodsDetailedUuid()));

                Comment comment= iCommentService.selectOne(new EntityWrapper<Comment>().eq("user_uuid",user.getUuid())
                        .eq("goods_uuid",goodsDetailed.getGoodsUuid()));
                if(comment==null){
                    OrderDetailedWithGoodsUuid orderDetailed=new OrderDetailedWithGoodsUuid(goodsDetailed.getGoodsUuid(),orderDetailedList);

                    orderDetailedsWithGoodsuuid.add(orderDetailed);

                }
            }
        }

        return ResponseBean.createSuccess().addData("orderDetailedsWithGoodsuuid",orderDetailedsWithGoodsuuid);

    }
    /**
 * 获取支付和退款记录
 */
@RequestMapping("/getmoney")
    public ResponseBean getMoney(HttpServletRequest request,Integer status,PageBean pageBean)throws Exception{
    String userUuid = JwtUtil.getUuidByToken(request);
    List<Order> orders=new ArrayList<>();
    /*String userUuid="b17200315c91433688e579f5acdcabe0";*/
    Page page= PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
    if(status==1){
         orders=iOrderService.selectList(new EntityWrapper<Order>().eq("user_uuid",userUuid)
                .eq("status",1).orderBy("createtime",false));
    }
    if(status==6){
         orders=iOrderService.selectList(new EntityWrapper<Order>().eq("user_uuid",userUuid)
                .eq("status",6).orderBy("createtime",false));
    }

    pageBean= new PageBean(page.getPageNum(),page.getPageSize(), (int) page.getTotal());
    return ResponseBean.createSuccess().addData("orders",orders).addData("pageBean",pageBean);
}
    /**
     * 生成充值订单
     */
    @RequestMapping("/createorderone")
    public ResponseBean getOreder(double aggregateAmount,HttpServletRequest request)throws Exception{

        String userUuid = JwtUtil.getUuidByToken(request);
        /*String uid=RandomUtils.makeUUID();*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String orderSn=OrderConst.PAYCODE3+ sdf.format(new Date()) + RandomUtils.makeRandomDigit6() + RandomUtils.getNBitRandomDigit(4);
        UserDeposit userDeposit=new UserDeposit();
        userDeposit.setUid(userUuid);
        userDeposit.setOrderSn(orderSn);
        userDeposit.setPayCode(OrderConst.PAYCODE1);
        //  BigDecimal decimalB = new BigDecimal(order.getAggregateAmount());
        BigDecimal decimalB = new BigDecimal(aggregateAmount);
        // decimalB.setScale(2, BigDecimal.ROUND_HALF_UP);
        //  userDeposit.setMoney(decimalB);
        userDeposit.setMoney(decimalB.setScale(2, BigDecimal.ROUND_HALF_UP));
        userDeposit.setOrderTime(new Date());
        userDeposit.setOrderStatus(0);
        iUserDepositService.insert(userDeposit);
      /*  order.setUuid(orderuuid);
        order.setUserUuid(userUuid);
        order.setOrderid(orderid);
        order.setCreatetime(new Date());
        order.setsQuantity(1);
        order.setStatus(0);
        order.setPaySellerStatus(false);
        order.setConsigneeUuid("");
        order.setShopUuid("");
        order.setExpressPrice(0.0);
        order.setActualPrice(order.getAggregateAmount());
        order.setIntegral(0);
        iOrderService.insert(order);*/
        return ResponseBean.createSuccess().addData("order",userDeposit);
    }
    /**
     * 钱包支付
     */
    @RequestMapping("/zhifu")
    public ResponseBean ZhiFu(HttpServletRequest request,String orderid)throws Exception {

        String userUuid = JwtUtil.getUuidByToken(request);
       /* //查询提现记录
        List<UserWithdrawal> userWithdrawals = userWithdrawalService.selectList(new EntityWrapper<UserWithdrawal>()
                .eq("uid", userUuid).eq("status",OrderConst. withdrawalstatus0));
        double total = 0;
        for (UserWithdrawal uw : userWithdrawals) {
            double money = uw.getMoney().doubleValue();
            total += money;
        }*/
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        /*  double D=user.getMoney().doubleValue()-total;*/
        List<Order> orders = iOrderService.selectList(new EntityWrapper<Order>().eq("payid", orderid));
        if (orders.size()==0) {
            return ResponseBean.createError("不存在该订单，支付发生错误");
        }
        for(Order order : orders){
           /* Order order = iOrderService.selectOne(new EntityWrapper<Order>().eq("orderid", orderid1).eq("status",OrderConst.orderstatus0));
            if(order==null){
                return ResponseBean.createError("不存在"+orderid1+"定单");
            }*/
            order.setPaytype(OrderConst.PAYCODE2);
            order.setUpdatetime(new Date());
            order.setPaySellerStatus(true);
            order.setStatus(1);
            iOrderService.updateById(order);
            UserCartGoodsVo goods=iOrderDetailedService.selectGoods(order.getId());
            if(goods!=null){
            	if(goods.getAttributes().equals("{}") || goods.getAttributes()==null){
					userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",userUuid).eq("goods_uuid",goods.getGoods_uuid()).eq("isdeleted",false));
				}else{
					userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",userUuid).eq("goods_uuid",goods.getGoods_uuid()).eq("attributes",goods.getAttributes()).eq("ideleted",false));
				}

            }
             //销量增加
            List<OrderDetailed> orderDetailedsLists=iOrderDetailedService.selectList(new EntityWrapper<OrderDetailed>().eq("order_uuid",order.getUuid()));
            for(OrderDetailed orderDetailedList:orderDetailedsLists) {
                GoodsDetailed goodsDetailed = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("uuid", orderDetailedList.getGoodsDetailedUuid()));
                goodsDetailed.setSoldQuantity(goodsDetailed.getSoldQuantity()+orderDetailedList.getQuantity());
                iGoodsDetailedService.updateById(goodsDetailed);
            }



            UserDeposit userDeposit = new UserDeposit();
            userDeposit.setUid(order.getUserUuid());
            BigDecimal decimalB = new BigDecimal(order.getActualPrice());
            BigDecimal  decimal = decimalB.multiply(new BigDecimal(-1));
            userDeposit.setMoney(decimal);
            userDeposit.setOrderSn(order.getOrderid());
            userDeposit.setOrderTime(order.getCreatetime());
            userDeposit.setPayCode(OrderConst.PAYCODE);
            userDeposit.setOrderStatus(OrderConst.depositstatus1);
            iUserDepositService.insert(userDeposit);
        }
        double actualPrice=0;
        for (Order order : orders) {
            actualPrice += order.getActualPrice();
        }

        if(user.getMoney().doubleValue()<actualPrice)
        {
            return ResponseBean.createError("余额不足");
        }

        double A = user.getMoney().doubleValue();
        double B = A - actualPrice;
        BigDecimal C = new BigDecimal(B);
        if(C.doubleValue()<0){
            return ResponseBean.createError("支付失败");
        }
        user.setMoney(C);
        iUserService.update(user, new EntityWrapper<User>().eq("uuid", user.getUuid()));
        return ResponseBean.createSuccess("支付成功");
    }

    @PostMapping("/getNumber")
    public ResponseBean getNumber(HttpServletRequest request){

       String userUuid = JwtUtil.getUuidByToken(request);
       //  String userUuid="2c5006a745b1444a8d35eebb50e44960";
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        List<Integer> numbers = new ArrayList<Integer>();
        Integer waitPay=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.depositstatus0)
                .eq("user_uuid",user.getUuid()).eq("isdeleted",0));
        Integer waitSend=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.depositstatus1).eq("user_uuid",user.getUuid()));
        Integer waitGet=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.orderstatus2).eq("user_uuid",user.getUuid()));
        Integer waitComment=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.orderstatus4).eq("user_uuid",user.getUuid())
                               .eq("isdeleted",0));
        Integer cancel=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.orderstatus5).eq("user_uuid",user.getUuid()));
        Integer refund=iOrderService.selectCount(new EntityWrapper<Order>().eq("status",OrderConst.orderstatus8).eq("user_uuid",user.getUuid()));

        Integer cancelRefund=cancel+refund;
        numbers.add(waitPay);
        numbers.add(waitSend);
        numbers.add(waitGet);
        numbers.add(waitComment);
        numbers.add(cancelRefund);
        return ResponseBean.createSuccess().addData("count", numbers);
    }
    @PostMapping("/toPay")
    public ResponseBean toPay(String id,HttpServletRequest request){
        String userUuid = JwtUtil.getUuidByToken(request);
        // String userUuid="2c5006a745b1444a8d35eebb50e44960";
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        if(user==null){
            ResponseBean.createError("请先登录");
        }
        if(id==null){
            return ResponseBean.createError("订单id不能为空");
        }
        try{
            Order order=iOrderService.selectOne(new EntityWrapper<Order>().eq("id",id).eq("user_uuid",user.getUuid()));

            if(order==null){
                return ResponseBean.createError("该订单不存在");
            }
            if(order.getStatus().equals(0)){
                //合并支付payid
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String payid = sdf.format(new Date()) + RandomUtils.makeRandomDigit6() + RandomUtils.getNBitRandomDigit(4);

                order.setPayid(payid);
                order.setUpdatetime(new Date());
                iOrderService.updateById(order);
                return ResponseBean.createSuccess().addData("payid",payid);
            }
            return ResponseBean.createError("不是待支付订单");
        }catch (Exception e){
            return ResponseBean.createException("数据库异常,出现重复的数据");
        }
    }
    @PostMapping("/cxxd")
    public ResponseBean ChongXin(Integer id) {
        Order orderi = iOrderService.selectById(id);

        if(orderi==null){
            return ResponseBean.createError("不存在该订单");
        }
        orderi.setIsdeleted(true);
        orderi.setUpdatetime(new Date());
        iOrderService.updateById(orderi);
        return ResponseBean.createSuccess("重新下单成功");


//        Integer num = iOrderDetailedService.updateone(orderi.getUuid());
//        if (num != 0) {
//            return ResponseBean.createSuccess("重新下单成功");
//        }
//        return  ResponseBean.createError("重新下单失败");

    }
}
